package cn.homework.dao.impl;

import cn.homework.dao.PaymentDao;
import cn.homework.domain.MainType;
import cn.homework.domain.Payment;
import cn.homework.utils.JDBCUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author ACT
 */
public class PaymentDaoImpl implements PaymentDao {
    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());

    @Override
    public List<Payment> findPaymentMethod() {
        String sql = "select * from payment";
        List<Payment> list = template.query(sql, new BeanPropertyRowMapper<>(Payment.class));
        return list;
    }

    @Override
    public void delPaymentById(String id) {
        String sql = "delete from payment where id = ?";
        template.update(sql, id);
    }

    @Override
    public List<Payment> findPaymentCondition(Map<String, String[]> map) {
        String sql = "select * from payment  where 1 = 1 ";
        StringBuilder sb = new StringBuilder(sql);
        //遍历map
        Set<String> keySet = map.keySet();
        //定义参数的集合
        List<Object> params = new ArrayList<>();
        for (String key : keySet) {
            //排除条件信息
            if ("demand".equals(key)) {
                continue;
            }

            //获取values
            String values = map.get(key)[0];
            //判断是否有值
            if (values != null && !"".equals(values)) {
                //有值
                sb.append(" and " + key + " like ? ");
                params.add("%" + values + "%");
            }
        }
        sql = sb.toString();
        List<Payment> list = template.query(sql, new BeanPropertyRowMapper<>(Payment.class), params.toArray());
        return list;
    }

    @Override
    public void addPayment(Payment payment) {
        String sql = "insert into payment values(?, ?, ?)";
        template.update(sql, payment.getId(), payment.getPayment(), payment.getMsg());
    }
}
